package com.wyp168.leetcode;

import java.util.Arrays;

/**
 * @ClassName ThreeSumClosest
 * @Description TODO 最接近的三数之和
 * @Author wyp168
 * @Date 2022/7/25 10:32
 */
public class ThreeSumClosest {
    public static void main(String[] args) {
        int[] nums = {-1,2,1,-4};
        int target = 1;
        System.out.println(threeSumClosest(nums, target));
    }

    public static int threeSumClosest(int[] nums, int target) {
        //给数组排序
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        int sum;

        for (int i = 0; i < nums.length; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            while (start < end) {
                sum = nums[start] + nums[end] + nums[i];
                if (Math.abs(sum - target) < Math.abs(ans - target)) {
                    ans = sum;
                }

                if (sum > target) {
                    end --;
                } else if (sum < target) {
                    start ++;
                } else {
                    return ans;
                }
            }
        }
        return ans;
    }
}
